/*
 Copyright (C) 2009 QDSS.org
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.qdss.persist.support.schema;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.qdss.persist.Entity;
import org.qdss.persist.dialect.Dialect;
import org.qdss.persist.metadata.MetadataFactory;
import org.qdss.persist.util.SqlHelper;


/**
 * 
 * @author <a href="mailto:zhaofang123@gmail.com">FANGFANG ZHAO</a>
 * @since 0.1.0, 06/15/08
 * @version $Id: SchemaExport.java 55 2009-05-31 05:26:48Z zhaofang123@gmail.com $
 */
public class SchemaExport {

	final private MetadataFactory metadataFactory;
	final private Dialect dialect;
	final private Connection connect;
	
	public SchemaExport(MetadataFactory metadataFactory, Dialect dialect, Connection connect) {
		this.metadataFactory = metadataFactory;
		this.dialect = dialect;
		this.connect = connect;
	}

	@SuppressWarnings("deprecation")
	public void export(boolean drop, boolean createFK) {
		Entity[] entities = metadataFactory.getEntities();

		PreparedStatement pstmt = null;
		try {
			for (Entity entity : entities) {
				String[] sqls = new Table(entity, dialect).generateDDL(drop, createFK);

				pstmt = connect.prepareStatement("/* !NULL */");
				for (String sql : sqls) {
					pstmt.addBatch(sql);
					System.out.println(sql + "\n");
				}
				pstmt.executeBatch();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			SqlHelper.close(pstmt);
			SqlHelper.close(connect);
		}
	}
}
